package cn.jdy.plugins.service;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import cn.jdy.framework.db.hibernate.BaseDao;
import cn.jdy.framework.exception.BaseException;
import cn.jdy.framework.log.BaseLog;
import cn.jdy.framework.util.SpringUploadFile;
import cn.jdy.framework.util.StringUtil;
import cn.jdy.platform.entity.ConfValue;
import cn.jdy.plugins.entity.Attachment;
import cn.jdy.plugins.entity.BrandCredit;
import cn.jdy.plugins.entity.Company;
import cn.jdy.plugins.entity.CompanyContext;

@Service
public class CompanyContextService extends BaseDao<CompanyContext> {

  @Autowired
  private BrandCreditService brandCreditService;
  @Autowired
  private AttachmentService attachmentService;
  @Autowired
  private CompanyService companyService;
  
  /**
   * 按分类查询企业信息，用于手机端企业展示
   * 
   * @param displayStart
   * @param displayLength
   * @return
   */
  public List queryCompany(String type, int displayStart, int displayLength) {
    List list = null;
    try {
      String sql = "SELECT * FROM ConfValue confvalue0_ WHERE typeid = '24' AND confvalue0_.levels = '2'";
      if (StringUtil.isNotEmpty(type)) {
        sql += "-1".equals(type) ? " AND remark = '荐'"
            : " AND pid in (select id from ConfValue where typeid = '24' AND levels = '1' AND pid = '"
                + type + "')";
      }
      sql += " order by confvalue0_.sort ASC limit :start,:length";

      SQLQuery query = em().createSQLQuery(sql);
      query.addEntity(ConfValue.class);
      query.setParameter("start", displayStart);
      query.setParameter("length", displayLength);
      list = query.list();
    } catch (Exception e) {
      BaseLog.e(this.getClass(), "根据分类levels查找对应配置项异常！", e);
    }
    return list;
  }

  /**
   * 保存企业提交展示信息
   * 
   * @param context
   * @param myfiles
   * @param brandLogo
   * @param companyLogo
   * @param path
   * @param request
   * @throws IOException
   */
  @Transactional
  public void addCompanyContext(CompanyContext context, String[] attaIds, MultipartFile[] myfiles,
      MultipartFile brandLogo, MultipartFile companyLogo, String path, HttpServletRequest request)
      throws IOException, NoSuchFieldException, IllegalAccessException {
    String sep = System.getProperty("file.separator");
    String brandPath = "brandLog";
    Map<String, String> brandMap = SpringUploadFile.uploadFile(brandLogo, request, brandPath);
    context.setBrandLogo(brandMap.get("newUrl"));
    String companyPath = "companyLog";
    Map<String, String> companyMap = SpringUploadFile.uploadFile(companyLogo, request, companyPath);
    context.setCompanyLogo(companyMap.get("newUrl"));

    // 保存companyContext
    if (null == context.getId()) {
      super.save(context);
    } else {
      super.updateWithValidator(context);
      Company entity_old = context.getCompany();
//      Company company = new Company();
//      company.setId(entity_old.getId());
//      company.setAddress(entity_old.getAddress());
//      company.setBusinessAddress(entity_old.getBusinessAddress());
//      company.setCompanyName(entity_old.getCompanyName());
//      hibernateTemplate.merge(company);
      companyService.updateWithValidator(entity_old);
    }
    
    String attchPath = "credit";

    for (int i = 0, len = myfiles.length; i < len; i++) {
      MultipartFile myfile = myfiles[i];
      if (!myfile.isEmpty()) {
        String attachment_path = SpringUploadFile.uploadFile(myfile, request, attchPath).get(
            "newUrl");
        Attachment att = new Attachment();
        att.setIs_del(0);
        att.setPost_time(new Date());
        att.setAttachment_type(0);
        att.setAttachment_size(myfile.getSize());// 文件长度
        att.setOriginaFilename(myfile.getOriginalFilename());// 文件原名
        att.setAttachment_path(attachment_path);
        if (attaIds[i].trim().length() > 0) {
          att.setId(attaIds[i]);
          attachmentService.update(att);
        } else {
          String id = (String) attachmentService.save(att);
          // 保存附件和品牌的关联关系
          BrandCredit credit = new BrandCredit();
          credit.setAttchmentid(id);
          credit.setBrandId(String.valueOf(context.getId()));
          brandCreditService.save(credit);
        }
      }
    }
  }

  /**
   * 根据条件查询
   * 
   * @return
   */
  public List<CompanyContext> query(CompanyContext entity) {
    return super.find(null, entity.getiDisplayStart(), entity.getiDisplayLength());
  }

  /**
   * 根据条件查询
   * 
   * @return
   */
  public List<HashMap> queryList(CompanyContext entity) {
    String sql = "SELECT cc.id, cc.companyId, cc.brandName, cc.createDate, cc.state, c.companyName,"
        + " c.mainProduct  FROM `companycontext` cc,`company` c "
        + "WHERE cc.`companyId` = c.`id` " + "ORDER BY cc.createDate DESC" + " limit :start,:length";

    SQLQuery query = super.em().createSQLQuery(sql);// 执行本地查询，原生sql

    // 将查询寻结果转换为Map格式，解决多表查询或零散字段查询 映射取值问题
    query.setResultTransformer(Transformers.ALIAS_TO_ENTITY_MAP);

    query.setParameter("start", entity.getiDisplayStart());
    query.setParameter("length", entity.getiDisplayLength());

    return query.list();
  }

  /**
   * 审核企业提交的信息
   * 
   * @param brandId
   * @param status
   * @return
   */
  @Transactional
  public int updStatus(String brandId, String status, String advice) {
    try {
      String[] brandIds = brandId.split(",");
      int size = brandIds.length;
      Long[] longs = new Long[brandIds.length];
      for(int i = 0; i< size; ++i) {
        longs[i] = Long.parseLong(brandIds[i]);
      }
      // update companycontext t set t.state = ?1 ,t.advice = ?2 where id
      // in(brandIds)
      return super.update(longs, "state", Integer.parseInt(status), "advice", advice);
    } catch (Exception e) {
      BaseLog.e(this.getClass(), "信息出错", e);
      throw new BaseException("审核信息出错！", e);
    }
  }

}
